﻿using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using WebApplication1.Cmds;
using WebApplication1.Model;
using WebApplication1.Tools;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// AI网关控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AiGatewayController(IServiceProvider sp) : ControllerBase
    {
        [HttpGet("appwork/{id}")]
        public async Task<IActionResult> AppWork(string id)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "apps", $"{id}.json");
            if (!System.IO.File.Exists(path)) return Content($"未找到应用 {id}");
            var app = JsonSerializer.Deserialize<AppServiceModel>(System.IO.File.ReadAllText(path));
            if (app?.cmds == null) return Content($"无法解析应用 {id}");
            var resultDic = new Dictionary<string, object>();
            foreach (var item in app.cmds)
            {
                var r = await new HttpAgentCommand(sp).Execute(item.args);
                resultDic.Add(item.name, r);
            }
            return new JsonResult(resultDic);
        }
        [HttpGet("debug/wss")]
        public async Task<IActionResult> WssDebug()
        {
            return new ViewResult();
        }
        [HttpGet("urlagent")]
        public async Task<Stream> UrlAgent(string url)
        {
            var httpClient = new HttpClient();
            var r = await httpClient.GetAsync(url);
            return r.Content.ReadAsStream();
        }
    }


}
